<template>
  <div>
    <div class="search">
      <input class="search__input"
             type="text"
             v-model="searchInfo"
             placeholder="输入城市名称或拼音"/>
    </div>
    <div class="search-result" ref="searchWrapper" v-show="searchInfo">
      <div class="city__line">
        <div class="cityLine"
             v-for="item of list"
             :key="item.id"
             @click="handleCityChange(item.name)"
        >{{item.name}}</div>
        <div class="cityLine border-bottom"  v-show = "hasNoData">没有找到相关的城市</div>
      </div>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cityData: Object
  },
  data () {
    return {
      searchInfo: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    searchInfo () {
      if (!this.searchInfo) {
        clearTimeout(this.timer)
      } else {
        const that = this
        this.timer = setTimeout(() => {
          const info = that.searchInfo
          let res = []
          for (let i in this.cityData.cities) {
            that.cityData.cities[i].forEach((value) => {
              if (value.spell.indexOf(info) > -1 || value.name.indexOf(info) > -1) {
                res.push(value)
              }
            })
          }
          that.list = res
        }, 100)
      }
    }
  },
  methods: {
    handleCityChange (msg) {
      this.$store.commit('change', msg)
      this.$router.push('/')
    }
  },
  mounted () {
    if (!this.searchScroll) {
      this.searchScroll = new Bscroll(this.$refs.searchWrapper, {
        mouseWheel: true, click: true, tap: true
      })
    } else {
      this.searchScroll.refresh()
    }
  }
}
</script>

<style lang='scss' scoped>
  .search {
    position: fixed;
    margin-top: 92px;
    padding: 16px 20px;
    height: 92px;
    width: 100%;
    background: #3190e8;
    text-align: center;
    z-index: 2;
  }
  .search__input {
    height: 60px;
    width: 100%;
    padding-left: 20px;
    line-height: 60px;
    border-radius: 6px;
    text-align: center;
    font-size: 28px;/*px*/
    color: #666;
  }
  .search-result {
    overflow: hidden;
    position: absolute;
    top: 184px;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 3;
  }
  .city__line {
    width: 100%;
  }
  .cityLine {
    padding: 18px 30px 18px 20px;
    border-bottom: 1px solid #ccc;
    text-align: left;
  }
</style>
